package com.cold.demo.template.controller;

import com.cold.demo.template.mapper.CommonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class TestController {

    @Autowired
    CommonMapper commonMapper;

    @RequestMapping("/test1")
    @ResponseBody
    public Object test1(@RequestAttribute(required = false,name = "test") Object test) {
        commonMapper.init();
        Map<String,Object> map = new HashMap<>();
        map.put("time",System.currentTimeMillis());
        return map;
    }


    // 请求转发 http://127.0.0.1:81/template/test2
    @RequestMapping("/test2")
    public void test2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/index.html").forward(request, response);
    }

    // 重定向 http://127.0.0.1:81/template/test3
    @RequestMapping("/test3")
    public String test3(HttpServletResponse response) {
        return "redirect:https://www.baidu.com?test=123";
    }

    @RequestMapping("/test3-2")
    public void test3_2(HttpServletResponse response) throws IOException {
        response.sendRedirect("https://www.baidu.com");
    }

    // 会报错，因为进行了两次重定向
    @RequestMapping("/test3-3")
    public String test3_3(HttpServletResponse response) throws IOException {
        response.sendRedirect("https://www.baidu.com");
        return "redirect:https://www.baidu.com";
    }

    // 请求包含
    @RequestMapping("/test4")
    public void test4(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/index.html").include(request, response);
    }


    @RequestMapping("/test2/{hello}")
    @ResponseBody
    public Object hello(@PathVariable("hello") String hello,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        return System.currentTimeMillis();
    }

}
